<?php

namespace Project\ScrumBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Project\ScrumBundle\Classe\StatsEnum;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormError;

class AvancementType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add('refUserstorie', 'entity', array(
                    'class' => 'Project\ScrumBundle\Entity\Userstories',
                    'property' => 'role',
                    'label' => 'User story : ',
                    'query_builder' => function (\Doctrine\ORM\EntityRepository $er) {
                        return $er->createQueryBuilder('userstory')
                                ->where('userstory.statut != :param')
                                ->andWhere('userstory.affectation != :param2')
                                ->setParameters(array('param' => StatsEnum::VALIDE,'param2' => 0));
                    },
                ))
                ->add('avancement', 'text')
        ;

        $avancementValidator = function(FormEvent $event) {
                    $form = $event->getForm();
                    $avancementField = $form->get('avancement')->getData();
                    if (!(intval($avancementField) >= 0 && intval($avancementField) <= 100)) {
                        $form['avancement']->addError(new FormError("compris entre 1 et 100"));
                    }
                };

        // ajout du validateur
        $builder->addEventListener(FormEvents::POST_BIND, $avancementValidator);
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'Project\ScrumBundle\Entity\Affectation'
        ));
    }

    public function getName() {
        return 'project_scrumbundle_avancementtype';
    }

}
